﻿using Microsoft.Xna.Framework.Graphics;

namespace Assignment_2.Entities.Components
{
    // Vertex Position Texture Component
    class VptComponent : DrawComponent
    {
        public Texture2D Texture { get; set; }

        private readonly VertexPositionTexture[] _vertices;
        private readonly int[] _indices;

        private readonly VertexBuffer _vBuffer;
        private readonly IndexBuffer _iBuffer;

        public VptComponent(Entity owner, GraphicsDevice device, VertexPositionTexture[] vertices, int[] indices)
            : base(owner, device)
        {
            _vertices = vertices;
            _indices = indices;

            _vBuffer = new VertexBuffer(Device, typeof(VertexPositionTexture), _vertices.Length, BufferUsage.WriteOnly);
            _iBuffer = new IndexBuffer(Device, typeof(int), indices.Length, BufferUsage.WriteOnly);

            _vBuffer.SetData(_vertices);
            _iBuffer.SetData(indices);
        }

        public override void Draw(BasicEffect effect)
        {
            effect.World = Owner.ObjectWorld;

            effect.LightingEnabled = false;
            effect.VertexColorEnabled = false;
            effect.TextureEnabled = true;
            effect.Texture = Texture;

            foreach (var pass in effect.CurrentTechnique.Passes)
            {
                pass.Apply();
            }

            Device.SetVertexBuffer(_vBuffer);
            Device.Indices = _iBuffer;
            Device.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, _vertices, 0, _vertices.Length, _indices, 0, _indices.Length / 3);
        }
    }
}
